﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Wagner.Utilities;

namespace Wagner.SharePoint.Utilities
{
	internal class SchJob : OperationBase
	{
		internal SchJob()
		{}

		internal override void Run()
		{
			// -o SchJob -jobname "SPDev: Timer Job Tester" -url http://localhost -sch "daily at 20:00:00" -pause -debug

			string jobName = ValidateParameter("jobname", true, null);
			string url = ValidateParameter("url", true, null);
			string schedule = ValidateParameter("sch", true, null);
			
			ScheduleJob(jobName, url, schedule);
		}
		
		private void ScheduleJob(string jobname, string url, string schedule)
		{
			using (SPSite site = new SPSite(url))
			{
				Guid jobID = Helper.GetJobID(jobname, url);
				SPWebApplication webApp = site.WebApplication;
				SPJobDefinition job = webApp.JobDefinitions[jobID];

				SPSchedule newSchedule = SPSchedule.FromString(schedule);

				Console.WriteLine("Configuring new schedule:");
				Console.WriteLine("  Web App:      " + webApp.Name);
				Console.WriteLine("  Job Name:     " + job.Name);
				Console.WriteLine("  Old Schedule: " + job.Schedule.ToString());
				Console.WriteLine("  New Schedule: " + newSchedule.ToString());
				job.Schedule = newSchedule;
				job.Update(true);
				Console.WriteLine("Configuring new schedule completed successfully.");
			}
		}

		internal override string HelpSummary
		{
			get
			{
				return @"
-o SchJob 
     Configures the schedule for a timer job.";
			}
		}

		internal override string HelpDetail
		{
			get
			{
				string help = HelpSummary + @"
Usage:
  SPDev.exe -o SchJob -jobname ""<job name>"" -url <url> -sch ""<schedule>""
      
    Parameters: 
     -jobname ""job name""
       Name of the Timer Job for which the schedule is to configure.
 
     -url <url>
       Specifies the url of the SharePoint web application on the local machine
       for the timer job to be configured.
 
     -sch <schedule>
       The string expression of the new schedule to apply to the timer job.
 
Examples:
 SPDev.exe -o SchJob -jobname ""My Custom Job"" -url http://localhost -sch ""daily at 21:00:00""

";

				return help;
			}
		}

	}	
}
